package com.aynu.gulimall.product.service.impl;

import com.aynu.common.constant.ProductConstant;
import com.aynu.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.aynu.gulimall.product.dao.AttrGroupDao;
import com.aynu.gulimall.product.dao.CategoryDao;
import com.aynu.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.aynu.gulimall.product.entity.AttrGroupEntity;
import com.aynu.gulimall.product.entity.CategoryEntity;
import com.aynu.gulimall.product.service.CategoryService;
import com.aynu.gulimall.product.vo.AttrGroupRelationVo;
import com.aynu.gulimall.product.vo.AttrResponseVo;
import com.aynu.gulimall.product.vo.AttrVo;
import com.mysql.cj.util.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.aynu.common.utils.PageUtils;
import com.aynu.common.utils.Query;

import com.aynu.gulimall.product.dao.AttrDao;
import com.aynu.gulimall.product.entity.AttrEntity;
import com.aynu.gulimall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;
import org.w3c.dom.Attr;

import javax.annotation.Resource;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Resource
    AttrAttrgroupRelationDao attrAttrgroupRelationDao;

    @Resource
    CategoryDao categoryDao;

    @Resource
    AttrGroupDao attrGroupDao;

    @Resource
    CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    /*规格参数新增*/
    @Transactional
    @Override
    public void saveAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        //使用Spring提供的对象之间传值，属性名需要 一样
        //将attr数据复制到attrEntity
        BeanUtils.copyProperties(attr,attrEntity);
        //1、保存基本信息
        this.save(attrEntity);
        //2、保存关联关系
        if (attr.getAttrType()== ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() && attr.getAttrGroupId()!=null)
        {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
            attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
            //保存 连接group和attr的表的信息
            attrAttrgroupRelationDao.insert(attrAttrgroupRelationEntity);
        }


    }

    /*查询规格参数的列表*/
    @Override
    public PageUtils queryBaseAttrPage(Map<String, Object> params, String type, Long catelogId) {
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>()
                .eq("attr_type","base".equalsIgnoreCase(type)?
                        ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode():ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());

        //catelog :目录
        //判断cateLogId是否为0（默认值），如果不为零，查询菜单的的attr
        if (catelogId != 0)
        {
            wrapper.eq("catelog_id",catelogId);
        }

        //获取key的值，因为封装为map
        String key = (String) params.get("key");
        if (!StringUtils.isEmptyOrWhitespaceOnly(key))
        {
            //模糊查询[pms_attr]表,
            wrapper.and((wrapper1)->{
                wrapper1.eq("attr_id",key).or().like("attr_name",key);
            });
        }

        //分页信息查询
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );

        PageUtils pageUtils = new PageUtils(page);
        //获取分页记录列表
        List<AttrEntity> records = page.getRecords();

        //进行流式编程
        List<AttrResponseVo> responseVos = records.stream().map((attrEntity) -> {
            AttrResponseVo attrResponseVo = new AttrResponseVo();
            BeanUtils.copyProperties(attrEntity, attrResponseVo);

            //分类信息
            //1、根据AttrAttrGroupRelation的cateLogid，查询cateLogName
            CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
            if (categoryEntity != null) {
                attrResponseVo.setCatelogName(categoryEntity.getName());
            }

            //分组信息
            //2、根据AttrAttrGroupRelation的attrGroupid，查询attrGroup,然后再查询attrGroupName
            if ("base".equalsIgnoreCase(type))
            {
                AttrAttrgroupRelationEntity attrAttrgroup = attrAttrgroupRelationDao.selectOne(
                        new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));

                if (attrAttrgroup != null && attrAttrgroup.getAttrGroupId()!=null) {
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrAttrgroup.getAttrGroupId());
                    attrResponseVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
            return attrResponseVo;
        }).collect(Collectors.toList());

        pageUtils.setList(responseVos);
        return pageUtils;
    }

    /*修改的信息回显*/

    /**
     * root.args[0]:获取第一个参数的值
     * @param attrId
     * @return
     */
    @Cacheable(value = "attr",key = "'attrInfo:'+#root.args[0]")
    @Override
    public AttrResponseVo getAttrInfo(Long attrId) {
        AttrResponseVo attrResponseVo = new AttrResponseVo();
        //1、根据attrid查询attr的信息
        AttrEntity attrEntity = baseMapper.selectById(attrId);
        //复制对象属性
        BeanUtils.copyProperties(attrEntity,attrResponseVo);
        //2、查询attrgroup信息根据attrAttrgroupRelation
        AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationDao.selectOne(
                new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attrId));
        //如果不是销售属性
        if (attrEntity.getAttrType()==ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode())
        {
            if (attrAttrgroupRelationEntity!=null)
            {
                //查询分组信息
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrAttrgroupRelationEntity.getAttrGroupId());
                if (attrGroupEntity!=null)
                {
                    //设置响应信息
                    attrResponseVo.setAttrGroupId(attrGroupEntity.getAttrGroupId());
                    attrResponseVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }

            }
        }

        //3、查询分类信息和完整路径
        Long catelogId = attrEntity.getCatelogId();
        Long[] catelogPath = categoryService.findCatelogPath(catelogId);
        attrResponseVo.setCatelogPath(catelogPath);
        //查询分类信息
        CategoryEntity categoryEntity = categoryDao.selectById(catelogId);
        if (categoryEntity!=null)
        {
            //设置响应信息
            attrResponseVo.setCatelogId(catelogId);
            attrResponseVo.setCatelogName(categoryEntity.getName());
        }

        return attrResponseVo;
    }

    /*修改规格参数*/
    @Transactional
    @Override
    public void updateAttr(AttrVo attrVo) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrVo,attrEntity);
        //1、保存基本的信息，在attr表中
        this.updateById(attrEntity);

        //如果不是销售属性
        if (attrEntity.getAttrType()==ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode())
        {
            //2、保存attrattrgroup表的信息
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrGroupId(attrVo.getAttrGroupId());
            attrAttrgroupRelationEntity.setAttrId(attrVo.getAttrId());
            //判断是否进行了修改，如果没有进行插入操作
            Integer count = attrAttrgroupRelationDao.selectCount(
                    new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrVo.getAttrId()));
            if (count>0)
            {
                //QueryWrapper  --使用，在不需要全部更新的时候，更新某个值时使用，如果本来没有值则需要进行插入操作
                attrAttrgroupRelationDao.update(attrAttrgroupRelationEntity,
                        new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attrVo.getAttrId()));
            }else {
                //因为原来字段没有值，所以进行新增
                attrAttrgroupRelationDao.insert(attrAttrgroupRelationEntity);
            }
        }

    }

    /**
     * 根据分组id查找关联的所有属性（规格参数）
     * @param attrgroupId
     * @return
     */
    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {
        List<AttrAttrgroupRelationEntity> entities = attrAttrgroupRelationDao.selectList(
                new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));
        //流式编程，取出所有的attr.getAttrId()
        List<Long> collect = entities.stream().map((attr) -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());

        List<AttrEntity> list=null;
        if (!collect.isEmpty())
        {
            list = this.listByIds(collect);
        }

        return list;
    }

    @Override
    public void deleteRelation(AttrGroupRelationVo[] vos) {
        List<AttrAttrgroupRelationEntity> collect = Arrays.asList(vos).stream().map((item) -> {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(item, attrAttrgroupRelationEntity);
            return attrAttrgroupRelationEntity;
        }).collect(Collectors.toList());

        attrAttrgroupRelationDao.deleteBatch(collect);

    }

    /**
     * 获取当前分组没有关联的所有属性
     * @param params
     * @param attrgroupId
     * @return
     */
    @Override
    public PageUtils getNoRelationAttr(Map<String, Object> params, Long attrgroupId) {
        //1、当前分组只能关联自己所属分类里面的所有属性
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);
        Long catelogId = attrGroupEntity.getCatelogId();
        //2、当前分组只能关联别的分组，没有引用的属性
        //2.1）、当前分类下的其他分组
        List<AttrGroupEntity> groupEntity = attrGroupDao.selectList(
                new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
        /*.ne("attr_group_id",attrgroupId)*/
        List<Long> groupIds = groupEntity.stream().map((item) -> {
            return item.getAttrGroupId();
        }).collect(Collectors.toList());

        System.out.println("groupIds   "+groupIds);
        //2.2）、这些分组的关联属性
        List<AttrAttrgroupRelationEntity> relationEntities = attrAttrgroupRelationDao.selectList(
                new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", groupIds));

        List<Long> collect = relationEntities.stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());

        System.out.println("collect  "+collect);
        //2.3）、从当前分类中所有属性中移除这些属性
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>()
                .eq("catelog_id", catelogId).eq("attr_type",ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        String key = (String) params.get("key");
        if (!collect.isEmpty())
        {
            wrapper.notIn("attr_id", collect);
        }
        if (!StringUtils.isEmptyOrWhitespaceOnly(key))
        {
            wrapper.and(w->{
                w.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), wrapper);

        System.out.println(page.getRecords());
        PageUtils pageUtils = new PageUtils(page);

        System.out.println("list"+pageUtils.getList());
        return pageUtils;
    }

    @Override
    public List<Long> selectSearchAttrs(List<Long> attrIds) {
       return baseMapper.selectSearchAttrIds(attrIds);
    }

}